<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="title">即时通讯</text>
        <view class="header-right">
          <view class="add-icon" @click="showAddMenu">
            <text class="icon">+</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 聊天列表 -->
    <scroll-view
      class="chat-list"
      scroll-y="true"
      :enhanced="true"
      :bounces="true"
      :show-scrollbar="false"
      :scroll-anchoring="true"
      :fast-deceleration="false"
    >
      <view v-for="(user, index) in userList" :key="user.id" class="chat-item" @click="openChat(user)">
        <view class="avatar">
          <text class="avatar-text">{{ getDisplayName(user).charAt(0) }}</text>
          <!-- 未读消息红点 -->
          <view v-if="user.unreadCount > 0" class="unread-badge">
            <text class="unread-count">{{ user.unreadCount > 99 ? '99+' : user.unreadCount }}</text>
          </view>
        </view>
        <view class="chat-content">
          <view class="chat-header">
            <text class="friend-name">{{ getDisplayName(user) }}</text>
            <text class="chat-time">{{ formatTime(user.lastMessageTime) }}</text>
          </view>
          <view class="message-row">
            <text class="last-message" :class="{ 'unread-message': user.unreadCount > 0 }">{{ user.lastMessage || '点击开始聊天' }}</text>
            <!-- 静音图标 -->
            <view v-if="user.isMuted" class="mute-icon">
              <text>🔇</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>



    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text>加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && userList.length === 0" class="empty-state">
      <text class="empty-text">暂无好友</text>
      <text class="empty-hint">点击右下角"+"添加好友开始聊天</text>
    </view>



    <!-- 自定义底部导航栏 -->
    <TabBar :current="0" @change="onTabChange" />

    <!-- 添加菜单弹窗 -->
    <view v-if="showAddMenuModal" class="add-menu-modal" @click="hideAddMenu">
      <view class="add-menu" @click.stop>
        <view class="add-menu-item" @click="addFriend">
          <view class="menu-item-content">
            <text class="add-menu-icon">👤</text>
            <text class="add-menu-text">添加好友</text>
          </view>
        </view>
        <view class="add-menu-item" @click="openFriendManage">
          <view class="menu-item-content">
            <text class="add-menu-icon">👥</text>
            <text class="add-menu-text">好友申请</text>
            <text v-if="pendingRequestCount > 0" class="badge">{{ pendingRequestCount > 99 ? '99+' : pendingRequestCount }}</text>
          </view>
        </view>
        <view class="add-menu-item" @click="testUnreadMessage">
          <view class="menu-item-content">
            <text class="add-menu-icon">🧪</text>
            <text class="add-menu-text">测试未读消息</text>
          </view>
        </view>
        <view class="add-menu-item" @click="logout">
          <view class="menu-item-content">
            <text class="add-menu-icon">🚪</text>
            <text class="add-menu-text">退出登录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getFriendList, getPendingRequestCount, markSessionAsRead } from '@/utils/api.js'
import { connectWebSocket, closeWebSocket } from '@/utils/websocket.js'
import TabBar from '@/components/TabBar/TabBar.vue'

export default {
  components: {
    TabBar
  },
  data() {
    return {
      userInfo: null,
      userList: [],
      showAddMenuModal: false,
      pendingRequestCount: 0,
      loading: false
    }
  },

  onLoad() {
    this.checkLogin()
    this.loadUserInfo()
    this.loadFriendList()
    this.loadPendingRequestCount()
    this.initWebSocket()
  },

  onUnload() {
    closeWebSocket()
  },

  onShow() {
    this.loadFriendList()
    this.loadPendingRequestCount()
  },

  methods: {
    checkLogin() {
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },

    loadUserInfo() {
      this.userInfo = uni.getStorageSync('userInfo')
    },

    /**
     * 加载好友列表
     */
    async loadFriendList() {
      this.loading = true
      try {
        console.log('=== 开始加载好友列表 ===')
        const result = await getFriendList()
        console.log('好友列表API响应:', result)

        if (result.code === 200) {
          const friendData = result.data || []
          console.log('原始好友数据:', friendData)

          this.userList = friendData.map(user => ({
            ...user,
            id: user.userId || user.id,
            userId: user.userId || user.id,
            nickname: user.nickname || user.username,
            username: user.username,
            remark: user.remark, // 保留备注字段
            lastMessage: '点击开始聊天',
            lastMessageTime: new Date(),
            unreadCount: 0, // 初始化为0，后续通过API获取真实数据
            isMuted: false
          }))

          // 加载每个好友的未读消息数量
          this.loadUnreadCounts()

          console.log('处理后的好友列表:', this.userList)
        } else {
          console.error('获取好友列表失败:', result.message)
          uni.showToast({
            title: result.message || '获取好友列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取好友列表失败:', error)
        uni.showToast({
          title: '网络错误: ' + error.message,
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    /**
     * 加载待处理好友申请数量
     */
    async loadPendingRequestCount() {
      try {
        const result = await getPendingRequestCount()
        if (result.code === 200) {
          this.pendingRequestCount = result.data || 0
        }
      } catch (error) {
        console.error('获取待处理申请数量失败:', error)
      }
    },

    initWebSocket() {
      const token = uni.getStorageSync('token')
      if (token) {
        connectWebSocket(token, (message) => {
          console.log('收到消息:', message)
          if (message.type === 'chat') {
            // 更新对应好友的最后消息
            const userIndex = this.userList.findIndex(user =>
              (user.userId || user.id) === message.fromUserId
            )
            if (userIndex !== -1) {
              const user = this.userList[userIndex]
              user.lastMessage = message.content
              user.lastMessageTime = new Date(message.sendTime || new Date())
              user.unreadCount = (user.unreadCount || 0) + 1

              // 保存未读数量到本地存储
              this.saveUnreadCount(user.userId || user.id, user.unreadCount)

              // 将有新消息的好友移到列表顶部
              this.userList.splice(userIndex, 1)
              this.userList.unshift(user)

              // 显示消息预览
              const preview = message.content.length > 20 ?
                message.content.substring(0, 20) + '...' : message.content

              uni.showToast({
                title: `${this.getDisplayName(user)}: ${preview}`,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    },

    async openChat(user) {
      const userId = user.userId || user.id
      const displayName = this.getDisplayName(user)

      console.log('打开聊天:', { userId, displayName, user })

      // 标记会话为已读（清除未读消息数）
      try {
        await markSessionAsRead(userId)
        // 清除本地未读消息数
        user.unreadCount = 0
        // 清除本地存储的未读数量
        this.saveUnreadCount(userId, 0)
      } catch (error) {
        console.error('标记会话已读失败:', error)
        // 即使标记失败也清除本地显示，避免影响用户体验
        user.unreadCount = 0
        this.saveUnreadCount(userId, 0)
      }

      uni.navigateTo({
        url: `/pages/chatDetail/chatDetail?userId=${userId}&nickname=${encodeURIComponent(displayName)}`
      })
    },

    /**
     * 加载所有好友的未读消息数量
     */
    async loadUnreadCounts() {
      // 目前未读消息数量主要通过WebSocket实时更新
      // 这里可以实现从本地存储或服务器获取未读数量的逻辑
      try {
        // 从本地存储获取未读消息数量
        for (let user of this.userList) {
          const storageKey = `unread_${user.userId || user.id}`
          const unreadCount = uni.getStorageSync(storageKey) || 0
          user.unreadCount = unreadCount
        }
      } catch (error) {
        console.error('加载未读消息数量失败:', error)
      }
    },

    /**
     * 保存未读消息数量到本地存储
     */
    saveUnreadCount(userId, count) {
      try {
        const storageKey = `unread_${userId}`
        uni.setStorageSync(storageKey, count)
      } catch (error) {
        console.error('保存未读消息数量失败:', error)
      }
    },

    showAddMenu() {
      this.showAddMenuModal = true
    },

    hideAddMenu() {
      this.showAddMenuModal = false
    },

    /**
     * 处理底部导航栏切换
     */
    onTabChange(index) {
      console.log('切换到标签:', index)
    },

    getDisplayName(user) {
      if (user.remark && user.remark.trim()) {
        return user.remark
      }
      return user.nickname || user.username || '未知用户'
    },

    openTest() {
      this.hideAddMenu()
      uni.navigateTo({
        url: '/pages/test/test'
      })
    },



    addFriend() {
      this.hideAddMenu()
      uni.navigateTo({
        url: '/pages/addFriend/addFriend'
      })
    },

    openFriendManage() {
      this.hideAddMenu()
      uni.navigateTo({
        url: '/pages/friendRequests/friendRequests'
      })
    },

    /**
     * 测试未读消息功能
     */
    testUnreadMessage() {
      this.hideAddMenu()
      if (this.userList.length > 0) {
        const user = this.userList[0]
        user.unreadCount = (user.unreadCount || 0) + 1
        user.lastMessage = '这是一条测试消息'
        user.lastMessageTime = new Date()

        // 保存到本地存储
        this.saveUnreadCount(user.userId || user.id, user.unreadCount)

        // 将用户移到顶部
        this.userList.splice(0, 1)
        this.userList.unshift(user)

        uni.showToast({
          title: '测试消息已添加',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '没有好友可以测试',
          icon: 'none'
        })
      }
    },

    logout() {
      this.hideAddMenu()
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除所有可能的认证相关存储
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            uni.removeStorageSync('ai_tutor_token')
            uni.removeStorageSync('ai_tutor_user')
            uni.removeStorageSync('ai_tutor_permissions')
            uni.removeStorageSync('phone')
            uni.removeStorageSync('username')
            uni.removeStorageSync('lastLoginUser')
            
            // 清除所有本地存储（彻底清理）
            try {
              uni.clearStorageSync()
            } catch (e) {
              console.log('清除存储失败:', e)
            }
            
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }
        }
      })
    },

    /**
     * 格式化时间显示
     */
    formatTime(time) {
      if (!time) return ''

      const now = new Date()
      const msgTime = new Date(time)
      const diff = now - msgTime

      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'

      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)

      if (msgTime >= today) {
        return msgTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else if (msgTime >= yesterday) {
        return '昨天'
      } else {
        return msgTime.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  height: 88rpx;
}

.title {
  color: white;
  font-size: 36rpx;
  font-weight: 500;
}

.add-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
}

.icon {
  color: white;
  font-size: 32rpx;
}

.chat-list {
  margin-top: 108rpx;
  padding-top: 30rpx; /* 增加顶部内边距 */
  height: calc(100vh - 108rpx - 100rpx - 30rpx); /* 调整高度以适应内边距 */
  background: white;
  padding-bottom: 20rpx;
  /* 优化滚动性能 */
  will-change: scroll-position;
  -webkit-overflow-scrolling: touch;
  contain: layout style paint;
  /* 启用硬件加速 */
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  /* 优化渲染性能 */
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  /* 优化渲染性能 */
  contain: layout style;
  will-change: auto;
  /* 启用硬件加速 */
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.avatar-text {
  color: white;
  font-size: 32rpx;
  font-weight: 600;
}

/* 未读消息红点 */
.unread-badge {
  position: absolute;
  top: -6rpx;
  right: -6rpx;
  min-width: 36rpx;
  height: 36rpx;
  background: linear-gradient(135deg, #ff4757 0%, #ff3838 100%);
  border-radius: 18rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid white;
  box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.4);
  animation: pulse-red 2s infinite;
}

.unread-count {
  color: white;
  font-size: 20rpx;
  font-weight: 700;
  line-height: 1;
  padding: 0 6rpx;
}

@keyframes pulse-red {
  0% {
    transform: scale(1);
    box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.4);
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 4rpx 16rpx rgba(255, 71, 87, 0.6);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.4);
  }
}

.chat-content {
  flex: 1;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.friend-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.chat-time {
  font-size: 24rpx;
  color: #999;
}

.message-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.last-message {
  font-size: 28rpx;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-message {
  color: #333;
  font-weight: 600;
}

.mute-icon {
  margin-left: 16rpx;
  font-size: 24rpx;
  opacity: 0.6;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.add-menu-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 2000;
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  padding: 108rpx 30rpx 0 0;
}

.add-menu {
  background: #2c2c2c;
  border-radius: 12rpx;
  overflow: hidden;
  min-width: 240rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
  animation: slideIn 0.2s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20rpx) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.add-menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx 40rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.08);
  transition: background-color 0.2s ease;
}

.add-menu-item:last-child {
  border-bottom: none;
}

.add-menu-item:active {
  background: rgba(255, 255, 255, 0.1);
}

.menu-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 24rpx;
}

.add-menu-icon {
  font-size: 36rpx;
  color: #ffffff;
  width: 40rpx;
  text-align: center;
}

.add-menu-text {
  color: #ffffff;
  font-size: 30rpx;
  font-weight: 400;
  flex: 1;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 100rpx 40rpx;
  color: #999;
  font-size: 28rpx;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 20rpx;
  display: block;
}

.empty-hint {
  font-size: 24rpx;
  color: #ccc;
  display: block;
}

.badge {
  background: #ff4757;
  color: white;
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 24rpx;
  min-width: 36rpx;
  text-align: center;
  line-height: 1;
  font-weight: 500;
  box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.3);
}

.notification-badge {
  position: absolute;
  top: -5rpx;
  right: 10rpx;
  background: #ff4757;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 20rpx;
  min-width: 24rpx;
  text-align: center;
  line-height: 1.2;
}


</style>